package protocol.work.connection.data;

import java.util.Map;

import protocol.common.entity.HttpConnConfig;
import protocol.work.connection.AbstractConnection;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import com.ibatis.sqlmap.client.SqlMapClient;

public class DataUpdateConnection extends AbstractConnection{
	protected JedisPool jedisPool;
	protected String queryPrefix;
	protected SqlMapClient sqlMapClient;
	protected HttpConnConfig httpConnConfig;
	
	public DataUpdateConnection(SqlMapClient sqlMapClient,HttpConnConfig httpConnConfig){
		super(httpConnConfig.getChannle());
		this.sqlMapClient = sqlMapClient;
		this.httpConnConfig = httpConnConfig;
		this.queryPrefix = this.httpConnConfig.getReportCacheKey();
		super.setName("QueryData-"+this.httpConnConfig.getChannle());
	}
	
	public void run(){
		while(super.initMark){
			try{
				Jedis jedis = this.getJedis();
  				String key = jedis.lpop(this.queryPrefix);
				if(key!=null){
					Map<String,String> map = jedis.hgetAll(key);
					String dataType = map.remove("DataType");
					try{
						if(dataType.equals("Submit")){
							long timeMark = System.currentTimeMillis();
							int row = sqlMapClient.update("DataPersistence.UpdateSmsSubmit",map);
							logger.info("<数据录入> 提交回执:"+(map.get("SubmitDesc"))+",网关MSGID:"+map.get("MsgId")+",耗时："+( System.currentTimeMillis()-timeMark)+"Ms,更新条数:"+row);
						}else if(dataType.equals("Report")){
							long timeMark = System.currentTimeMillis();
							int row = sqlMapClient.update("DataPersistence.UpdateSmsReport",map);
							logger.info("<数据录入> 回执报告:"+(map.get("REPORT_DESC"))+",网关MSGID:"+map.get("MSG_ID")+",耗时："+( System.currentTimeMillis()-timeMark)+"Ms,更新条数:"+row);
						}else if(dataType.equals("Deliver")){
							long timeMark = System.currentTimeMillis();
							sqlMapClient.insert("DataPersistence.InsertDeliver",map);
							logger.info("<数据录入> 上行短信:"+(map.get("SrcTerminalId"))+",内容:"+(map.get("MsgContent"))+",耗时："+( System.currentTimeMillis()-timeMark)+"Ms");
						}
					}catch (Exception e) {
					}finally{
						jedis.del(key);
						this.saveErrorMap(jedis,key,map);
						this.returnJedis(jedis);
					}
				}else{
					this.returnJedis(jedis);
					super.threadSleep(5000L);
				}
			}catch (Exception e) {
				super.exceptionHandle(e);
			}
		}
	}
	
	private void saveErrorMap(Jedis jedis,String key,Map<String,String> map){
		if(map!=null){
			Object errorObj = map.get("ErrorCount");
			if(errorObj == null){
				map.put("ErrorCount","1");
			}else{
				int errorCount = Integer.parseInt(errorObj.toString());
				if(errorCount<=3){
					map.put("ErrorCount",String.valueOf(++errorCount));
					jedis.del(key);
					jedis.hmset(key, map);
					jedis.lpush(this.queryPrefix,key);
				}
			}
		}
	}
	
}
